from sklearn import linear_model
import numpy as np
import matplotlib.pyplot as plt

# 读取数据
with open('.\\test3\\LinearRegression\\lr2_data.txt', 'r') as file:
    datas = file.readlines()
# 转为np数据
datas = [data.strip('\n') for data in datas]
datas = [data.split('\t') for data in datas]
datas = np.array(datas, dtype=float)
x_train = datas[:, 1].reshape(-1, 1)# scikit的线性回归的x默认是一个多feature的数据，需要是矩阵格式，所以reshape一下
y_train = datas[:, 2]

# 线性回归
model = linear_model.LinearRegression()
model.fit(x_train, y_train)

# 绘图
fig,(ax1) = plt.subplots(1,1,constrained_layout = True,figsize = (12,8))
ax1.scatter(x_train.flatten(),y_train,c='r',label='Actual Values')#y_train不用flatten，因为y本来就是1D的。x被认为是2D的
ax1.plot(x_train.flatten(),model.predict(x_train),c='b',label='Prediction')
plt.show()